package com.yonyou.crm.common.rest.apputil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yonyou.crm.bpub.initData.entity.InitDataSubVO;
import com.yonyou.crm.bpub.initData.entity.InitDatasItemVO;
import com.yonyou.crm.bpub.initData.entity.InitDatasListItemVO;
import com.yonyou.crm.bpub.initData.entity.InitParamItemVO;
import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.rest.util.RequestUtil;

public class AppRequestUtil {
	
	private final static Logger logger = LoggerFactory.getLogger(RequestUtil.class);
	
	/**
	 * 处理省市区的值
	 * @param headerJson
	 * @param itemKey
	 * @param value
	 */
	public static void getPCDValue(JSONObject headerJson, String itemKey, Object value) {
		if (value != null && !value.equals("")) {
			String[] itemKeyStrings = itemKey.split("_");
			String[] idStrings = String.valueOf(value).split("_");
			for (int m = 0; m<itemKeyStrings.length; m++) {
				headerJson.put(itemKeyStrings[m], idStrings[m]);
			}
		}
	}
	
	/**
	 * 处理多个值(以_分隔)
	 * @param headerJson
	 * @param itemKey
	 * @param value
	 */
	public static void getMulValue(JSONObject headerJson, String itemKey, Object value) {
		if (value != null && !value.equals("")) {
			String[] itemKeyStrings = itemKey.split("_");
			String[] idStrings = String.valueOf(value).split("_");
			for (int m = 0; m<itemKeyStrings.length; m++) {
				headerJson.put(itemKeyStrings[m], idStrings[m]);
			}
		}
	}
	
	/**
	 * 获得param对象
	 * @param request http请求对象
	 * @return
	 * @throws CrmMessageException 
	 */
	@SuppressWarnings("unchecked")
	public static JSONObject getFormParamObject(HttpServletRequest request) throws CrmMessageException {
		JSONObject paramObject = RequestUtil.getParamObject(request);
		
		// 解析表头
		List<JSONObject> headerList = (List<JSONObject>) paramObject.get("headerlist");
		JSONObject headerJson = new JSONObject();
		for (int i = 0; i< headerList.size(); i++) {
			Map<String, Class> classMap = new HashMap<String, Class>();
			classMap.put("itemdatalist", InitDatasItemVO.class);
			classMap.put("paramlist", InitParamItemVO.class);
			
			InitDatasListItemVO headerVO = new InitDatasListItemVO();
			try {
				headerVO = (InitDatasListItemVO)JSONObject.toBean(headerList.get(i), InitDatasListItemVO.class, classMap);
			} catch(Exception e) {
				throw new CrmMessageException("参数格式错误");
			}
			
			ArrayList<InitDatasItemVO> dataList = headerVO.getItemdatalist();
			Integer dataSize = dataList.size();
			if (dataList != null && dataSize > 0) {
				InitDatasItemVO headerItemVO = (InitDatasItemVO)dataList.get(0);
				Object dataid = headerItemVO.getDataid();
				Object datavalue = headerItemVO.getDatavalue();
				Object value = dataid;
				if (dataid == null || dataid.equals("")) {
					value = datavalue;
				}
			
				String itemKey = headerVO.getItemkey();
				if (dataSize > 1) {
					//TODO 多选时取值，待验证
					for (int j = 1; j < dataSize; j++) {
						headerItemVO = (InitDatasItemVO)dataList.get(j);
						dataid = headerItemVO.getDataid();
						datavalue = headerItemVO.getDatavalue();
						Object MulValue = dataid;
						if (dataid == null || dataid.equals("")) {
							MulValue = datavalue;
						}
						value = value + "," + MulValue;
					}
					headerJson.put(itemKey, value);
				} else {
					if (itemKey.equals("address") || itemKey.equals("street")) {
						headerJson.put(itemKey, value);
						List<InitParamItemVO> paramlist = headerItemVO.getParamlist();
						// 处理详情地址中的经纬度信息
						if ((paramlist != null) && (paramlist.size() > 0)) {
							for(InitParamItemVO info : paramlist) {
								headerJson.put(info.getParamkey(), info.getParamvalue());
							}
						}
					} else if (itemKey.equals("province_city_district")) {
						getPCDValue(headerJson, itemKey, value);
					} else if (itemKey.contains("_")) {
						getMulValue(headerJson, itemKey, value);
					} else {
						headerJson.put(itemKey, value);
						
					}
				}
				//TODO 处理paramlist(一部分需要处理，一部分不需要处理) 详细地址中的已处理
				
			}
		}

		// 解析表体 TODO
		List<JSONObject> bodyList = (List<JSONObject>) paramObject.get("bodylist");
		JSONObject bodyJsonObject = new JSONObject();
		for (int i = 0; i< bodyList.size(); i++) {
			Map<String, Class> classMap = new HashMap<String, Class>();
			classMap.put("bodydatalist", InitDatasListItemVO.class);
			classMap.put("itemdatalist", InitDatasItemVO.class);
			classMap.put("paramlist", InitParamItemVO.class);
			
			InitDataSubVO subVO = new InitDataSubVO();
			try {
				subVO = (InitDataSubVO)JSONObject.toBean(bodyList.get(i), InitDataSubVO.class, classMap);
			} catch(Exception e) {
				throw new CrmMessageException("参数格式错误");
			}
			JSONArray bodyJsonArray = new JSONArray();
			List<InitDatasListItemVO> listItemVOs = subVO.getBodydatalist();
			String bodyMark = subVO.getBodymark();
			if (bodyJsonObject.containsKey(bodyMark)) {
				bodyJsonArray = bodyJsonObject.getJSONArray(bodyMark);
			}
			JSONObject bodyJson = new JSONObject();
			bodyJson.put("editState", subVO.getAction());
			for (InitDatasListItemVO listItemVO:listItemVOs) {
				ArrayList<InitDatasItemVO> itemVOs = listItemVO.getItemdatalist();
				for (InitDatasItemVO itemVO:itemVOs) {
					Object dataid = itemVO.getDataid();
					Object datavalue = itemVO.getDatavalue();
					Object value = dataid;
					if (dataid == null || dataid.equals("")) {
						value = datavalue;
					}
					String itemKey = listItemVO.getItemkey();
					if (itemKey.equals("province_city_district")) {
						getPCDValue(headerJson, itemKey, value);
					} else if (itemKey.contains("_")) {
						getMulValue(headerJson, itemKey, value);
					} else {
						bodyJson.put(listItemVO.getItemkey(), value);
					}
				}
			}
			bodyJsonArray.add(bodyJson);
			bodyJsonObject.put(bodyMark, bodyJsonArray);
		}

		JSONObject dataJsonObject = new JSONObject();
		dataJsonObject.put("header", headerJson);
		dataJsonObject.put("body", bodyJsonObject);
		// 解析相关业务对象 
		JSONObject relateMap = (JSONObject) paramObject.get("relatemap");
		if (relateMap != null) {
			dataJsonObject.put("relateMap", relateMap);
		}
		// 解析业务子类型 
		String subbnstype = paramObject.get("subbnstype").toString();
		if (subbnstype != null) {
			dataJsonObject.put("subBnsType", subbnstype);
		}
		
		return dataJsonObject;
	}
	
	public static <T> T getVO(JSONObject jsonObject, Class<T> clazz) {
		return getVO(jsonObject, clazz, null);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getVO(JSONObject jsonObject, Class<T> clazz, Map<String, Class<?>> fieldClassMap) {
		if (jsonObject != null && !jsonObject.isNullObject()) {
			return (T) JSONObject.toBean(jsonObject, clazz, fieldClassMap);
		}
		return null;
	}
	
	public static <T> List<T> getVOList(JSONArray jsonArray, Class<T> clazz) {
		return getVOList(jsonArray, clazz, null);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> List<T> getVOList(JSONArray jsonArray, Class<T> clazz, Map<String, Class<?>> fieldClassMap) {
		
		List<T> voList = new ArrayList<T>();
		if (jsonArray != null && jsonArray.size() > 0) {
			
			for (Object obj : jsonArray) {
				voList.add((T)JSONObject.toBean((JSONObject)obj, clazz, fieldClassMap));
			}
		}
		return voList;
	}
	
}
